/**
 *
 */
package 锁;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.junit.Test;

/**
 *
 * @Title:
 * @author zhoujie
 * @date 2019年1月18日 上午9:38:37 
 *
 */
public class TReentrantLock {
    static volatile int k = 1;

    /**
     * 两个线程交替输出到100
     */
    @Test
    public void test01() {

        Lock lock = new ReentrantLock();
        Condition jicon = lock.newCondition();//基数条件
        Condition oucon = lock.newCondition();//偶数条件

        Thread t1 = new Thread(() -> {
            while (k <= 99) {
                if (k % 2 != 0) {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + ":" + (k++));
                    try {
                        oucon.signal();
                        jicon.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    lock.unlock();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (k <= 100) {
                if (k % 2 == 0) {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + ":" + (k++));
                    try {
                        jicon.signal();
                        //要小于100才睡不然 主线程一直等他睡觉 没人叫起他
                        if (k <= 100) {
                            oucon.await();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    lock.unlock();
                }
            }
        });
        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
